import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/cates',
    name: 'cates',
    component: () => import('@views/Cates'),
    meta:{
      needLogin:false
    }
  },
  {
    path: '/itemlist',
    name: 'itemlist',
    component: () => import('@views/ItemList'),
    meta:{
      needLogin:false
    }
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import('@views/Mine'),
    meta:{
      needLogin:true
    }
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@views/Cart'),
    meta:{
      needLogin:false
    }
  },
  {
    path:'/detail/:id',
    name:'detail',
    component: () => import('@views/Detail'),
    meta:{
      needLogin:false
    }
  },
  {
    path:'/itemLists/:categoryId', 
    name:'itemLists',
    component: () => import('@views/ItemList'),
    meta:{
      needLogin:false
    }
  },
  {
    path:'/order', 
    name:'order',
    component: () => import('@views/Order'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/login', 
    name:'login',
    component: () => import('@views/Login'),
    meta:{
      needLogin:false
    }
  },
  {
    path:'/addressLists', 
    name:'addressLists',
    component: () => import('@views/AddressLists'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/addContact', 
    name:'addContact',
    component: () => import('@views/AddContact'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/editContact/:index', 
    name:'editContact',
    component: () => import('@views/EditContact'),
    meta:{
      needLogin:true
    }
  },
  {
    path:'/search', 
    name:'search',
    component: () => import('@views/Search'),
    meta:{
      needLogin:false
    }
  },
  {
    path:'/searchResult', 
    name:'searchResult',
    component: () => import('@views/searchResult'),
    meta:{
      needLogin:false
    }
  }
]

const router = new VueRouter({   
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 登录鉴权
router.beforeEach((to,from,next)=>{
  // 判断用户是否直接去登录/注册页面,若是去这些页面，则直接放行
  if (to.fullPath === '/login' || to.fullPath === '/register') {
    next()
  }else{
    // 判断 目标路由是否需要登录
    if (to.meta.needLogin) {
      // 需要登录,获取 本地存储里面的 access_token，若有，则放行，否则重定向到登录页面
      const accessToken = localStorage.getItem('access_token')
      if (accessToken) {
        next()
      } else {
        next({
          name:'login',
          params:{
            from:to.fullPath
          }
        })
      }
    } else {
      // 若 目标路由 不需要登录，则直接放行
      next()
    }
  }
})

export default router
